package com.elitedatai.mchtest.manage.controller;


import com.dji.sdk.common.HttpResultResponse;
import com.dji.sdk.common.PaginationData;
import com.elitedatai.mchtest.common.model.CustomClaim;
import com.elitedatai.mchtest.manage.model.dto.UserListDTO;
import com.elitedatai.mchtest.manage.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import static com.elitedatai.mchtest.component.AuthInterceptor.TOKEN_CLAIM;


/**
 * 用户控制器，处理用户相关的HTTP请求
 */
@RestController
@RequestMapping("${url.manage.prefix}${url.manage.version}/users")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查询当前用户信息
     * @param request HTTP请求对象，用于获取用户凭证信息
     * @return 当前用户信息响应
     */
    @GetMapping("/current")
    public HttpResultResponse getCurrentUserInfo(HttpServletRequest request) {
        CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
        return userService.getUserByUsername(customClaim.getUsername(), customClaim.getWorkspaceId());
    }

    /**
     * 分页查询工作空间中的所有用户
     * @param page 当前页码
     * @param pageSize 每页大小
     * @param workspaceId 工作空间ID
     * @return 分页用户列表数据
     */
    @GetMapping("/{workspace_id}/users")
    public HttpResultResponse<PaginationData<UserListDTO>> getUsers(@RequestParam(defaultValue = "1") Long page,
                                                                    @RequestParam(value = "page_size", defaultValue = "50") Long pageSize,
                                                                    @PathVariable("workspace_id") String workspaceId) {
        PaginationData<UserListDTO> paginationData = userService.getUsersByWorkspaceId(page, pageSize, workspaceId);
        return HttpResultResponse.success(paginationData);
    }

    /**
     * 修改用户信息，仅包含MQTT账户信息，其他信息不可修改
     * @param user 用户信息DTO
     * @param workspaceId 工作空间ID
     * @param userId 用户ID
     * @return 操作结果响应
     */
    @PutMapping("/{workspace_id}/users/{user_id}")
    public HttpResultResponse updateUser(@RequestBody UserListDTO user,
                                         @PathVariable("workspace_id") String workspaceId,
                                         @PathVariable("user_id") String userId) {

        userService.updateUser(workspaceId, userId, user);
        return HttpResultResponse.success();
    }


}